<template>
  <div class="startBox">
    <img src="../../assets/startMeeting.png">

    <!-- 有任务 -->
    <div v-if="start" class="startMain">
      <div class="startTitle"><img src="../../assets/taskIcon.png">实时课堂进行中...</div>
      <div class="startInfo">
        <div class="startInfoLine">任务名: <span>{{ currentTask.name }}</span></div>
        <div class="startInfoLine">采样间隔时间: <span>{{ currentTask.sampling_interval }}秒</span></div>
        <div class="startInfoLine">班级: <span>{{ currentTask.class }}</span></div>
        <div class="startInfoLine">学生拉流地址: <span>{{ currentTask.videoStream1 }}</span></div>
        <div class="startInfoLine">老师拉流地址: <span>{{ currentTask.videoStream2 }}</span></div>
        <div class="startInfoLine">开始时间: <span>{{ changeToSpace(currentTask.start_time) }}</span></div>
        <div class="startInfoLine">持续时间: <span>{{ taskDuration }}</span></div>
      </div>
      <div class="btnLine">
        <div class="btnFinish" @click="stopCurrentTask()">结束</div>
        <div class="btnCheck" @click="checkCurrentClass()">去查看</div>
      </div>
    </div>

    <!-- 无任务-->
    <div v-else class="startMain">
      <div class="startTitle"><img src="../../assets/taskIcon.png">暂无课堂，可开启课堂行为分析任务</div>

      <!-- 自定义任务-教学分析 -->
      <div class="taskIn">
        <!-- <div class="taskInTitle"><el-radio  label="2" >自定义任务：</el-radio></div> -->
        <el-form ref="form" :model="form" :rules="rules" label-width="112px" class="taskInForm">

          <el-form-item label="模板：">
            <el-select v-model="templateValue" placeholder="请选择" clearable style="width:356px" @clear="clearTemplate">
              <el-option
                v-for="item in templateST"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                @click.native="changeSelect(item)"
              />
            </el-select>
            <el-tooltip v-if="currentTemplate.description" class="item" effect="light" :content="currentTemplate.description" placement="top">
              <i class="el-icon-warning-outline" style="font-size:22px;margin-left:4px;color:#1890ff" />
            </el-tooltip>
            <i v-else class="el-icon-warning-outline" style="font-size:22px;margin-left:4px;color:#dcdfe6" />
          </el-form-item>

          <el-form-item label="任务名：" prop="name">
            <el-input v-model="form.name" placeholder="请输入任务名" />
          </el-form-item>

          <el-form-item label="班级:" prop="department_id">
            <treeselect
              v-model="form.department_id"
              :options="deptOptions"
              :normalizer="normalizer"
              :disable-branch-nodes="true"
              :show-count="true"
              placeholder="请选择班级"
            />
          </el-form-item>

          <el-form-item label="ST采样时间:" prop="sampling_interval">
            <el-select v-model="form.sampling_interval" placeholder="请选择" style="width:100%">
              <el-option
                v-for="item in intervalOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="学生拉流地址:">
            <el-input v-model="form.videoStream1" placeholder="请输入地址" />
          </el-form-item>
          <el-form-item label="老师拉流地址:">
            <el-input v-model="form.videoStream2" placeholder="请输入地址" />
          </el-form-item>

          <div class="btnLine">
            <div class="btnCheck" @click="startNewTask('form')">开启任务</div>
          </div>
        </el-form>
      </div>

    </div>

  </div>
</template>

<script>
// 接口
import { listUser } from '@/api/system/user'
import { getTemplates, getTaskRunning, startTask, stopTask } from '@/api/main'
import { listDept } from '@/api/system/dept'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'StartClass',
  components: { Treeselect },

  data() {
    return {
      start: false,
      currentTask: {
        id: '',
        class: '',
        name: '',
        sampling_interval: null,
        videoStream1: null,
        videoStream2: null,
        start_time: null
      },
      taskStartTime: '', // 任务开始时间
      taskDuration: '', // 会议持续时间
      // templatesList:[],//模板列表
      templateST: [], // ST模板
      templateMeeting: [], // 会议模板
      templateValue: '',
      currentTemplate: {},
      showTemplate: false,
      taskTypes: [
        { value: 1, label: 'ST教学分析' },
        { value: 2, label: '会议督察' }
      ],
      intervalOptions: [
        { value: 5, label: '5秒' },
        { value: 15, label: '15秒' },
        { value: 30, label: '30秒' }
      ],
      // 表单校验
      rules: {
        department_id: [
          { required: true, message: '班级不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],
        sampling_interval: [
          { required: true, message: '请选择采样时间', trigger: 'change' }
        ]
      },

      form: {}, // 新增提交的表单
      memberBox: false, // 选择人员弹窗
      // 组织树选项
      deptOptions: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 遮罩层
      loading: true,
      // 用户表格数据
      userList: [],
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        page: 1,
        limit: 10,
        username: undefined,
        nickname: undefined,
        status: undefined,
        deptId: undefined
      },
      // 已选的人员
      selectedMember: []
      // selectedIds:[]

    }
  },
  computed: {
    selectedIds() {
      return this.selectedMember.map(item => item.id)
    }
  },
  watch: {
    // 根据名称筛选组织树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },

  mounted() {
    // 每秒更新时间差
    this.startTimer()
  },

  created() {
    // 获取模板
    this.getAllTemplates()
    // 获取正在进行的任务
    this.runingTask()
    // /////////
    this.getTreeselect()
  },
  beforeDestroy() {
    // 清理定时器
    clearInterval(this.timer)
  },
  methods: {
    back() {
      this.$router.back()
    },
    // 获取正在进行的任务
    runingTask() {
      getTaskRunning().then(response => {
        if (response.data.task_data.length === 0 || response.data.task_data.type === 2) {
          this.start = false
        } else {
          this.start = true
          this.currentTask = response.data.task_data
          this.currentTask.class = response.data.department.name
          this.taskStartTime = new Date(response.data.task_data.start_time).getTime()
        }
      })
    },

    startTimer() {
      this.timer = setInterval(() => {
        this.updateTimePassed()
      }, 1000) // 每秒更新一次
    },
    updateTimePassed() {
      const currentTime = Date.now() // 获取当前时间
      const diff = currentTime - this.taskStartTime // 计算时间差（毫秒）

      // 转换时间差为秒、分钟、小时、天等
      const seconds = Math.floor(diff / 1000)
      const minutes = Math.floor(seconds / 60)
      const hours = Math.floor(minutes / 60)
      const days = Math.floor(hours / 24)

      let timeString = ''

      // 根据持续时间来决定显示的格式
      if (days > 0) {
        // 超过24小时显示天数、小时、分钟和秒
        timeString = `${days}天 ${hours % 24}时 ${minutes % 60}分 ${seconds % 60}秒`
      } else if (hours > 0) {
        // 小于24小时显示小时、分钟和秒
        timeString = `${hours}时 ${minutes % 60}分 ${seconds % 60}秒`
      } else if (minutes > 0) {
        // 小于1小时显示分钟和秒
        timeString = `${minutes}分 ${seconds % 60}秒`
      } else {
        // 小于1分钟显示秒
        timeString = `${seconds}秒`
      }

      this.taskDuration = timeString
    },

    // 获取模板
    getAllTemplates() {
      getTemplates().then(response => {
        // this.templatesList=response.data
        // console.log('-------模板',this.templatesList)
        // st模板
        this.templateST = response.data.filter(item =>
          item.type === 1
        )
        // 会议模板
        this.templateMeeting = response.data.filter(item =>
          item.type === 2
        )
      })
    },
    // 选择模板
    changeSelect(val) {
      this.currentTemplate = val
      this.form = {
        sampling_interval: this.currentTemplate.sampling_interval,
        type: this.currentTemplate.type,
        department_id: this.currentTemplate.department_id,
        videoStream1: this.currentTemplate.videoStream1,
        videoStream2: this.currentTemplate.videoStream2
      }
    },
    // 清除选择模板
    clearTemplate() {
      this.currentTemplate = {}
      this.form = {}
    },

    /** 查询组织下拉树结构 */
    getTreeselect() {
      listDept().then(response => {
        this.deptOptions = response.data
      })
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    chooseMember() {
      this.memberBox = true
    },

    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id
      this.getList()
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true
      listUser(this.queryParams).then(response => {
        this.userList = response.data.items
        this.total = response.data.total
        this.loading = false
      }
      )
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      // 已选
      this.selectedMember = selection
    },
    rowKey(row) {
      return row.phone
    },
    handleClose(tag) {
      this.selectedMember.splice(this.selectedMember.indexOf(tag), 1)
    },

    // 开启新任务
    startNewTask(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.form.type = 1
          startTask(this.form).then(response => {
            if (response.code === 20000) {
              this.runingTask()
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 去查看实时课堂
    checkCurrentClass() {
      this.$router.push({ path: '/currentClass' })
    },
    // 结束任务
    stopCurrentTask() {
      const id = this.currentTask.id
      stopTask(id).then(response => {
        if (response.code === 20000) {
          this.runingTask()
          this.form = {}
        }
      })
    },
    // 字符替换
    changeToSpace(e) {
      return e.replace('T', ' ')
    }

  }
}
</script>

<style scoped>
.startBox{
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
}
.startBox img{
  width:644px;
  height: 610px;
  margin-left: 5%;
}
.startMain{
  flex: 1;
  display: flex;
  flex-direction: column;
  margin-left: 5%;
}
.startTitle{
  font-size: 30px;
  font-weight: bold;
  display: flex;
  align-items: center;
  color: #1364c2;
  margin-bottom:30px;
}
.startTitle img{
  width:34px;
  height: 34px;
  margin:5px 10px 0 0;
}
.startInfo{
  margin-top:20px;
  padding-left: 26px;
  margin-right: 15%;
}
.startInfoLine{
  min-height: 38px;
  line-height: 38px;
  border-bottom: 1px dashed #b4cbe3;
  margin-bottom: 10px;
  padding-left: 20px;
}
.startInfoLine span{
  color: #3d3d3d;
  margin-left: 10px;
}
.btnLine{
  display: flex;
  align-items: center;
}
.btnLine{
  margin-top:40px;
}
.btnFinish{
  width:136px;
  height: 52px;
  background: linear-gradient(#fa9d9a,#f2716f);
  display: flex;
  align-items: center;
  border-radius: 26px;
  justify-content: center;
  color: #fff;
  font-size: 24px;
  font-weight: bold;
  cursor: pointer;
  margin-right: 20px;
}
.btnFinish:hover{
  background: linear-gradient(#f5817e,#f2716f);

}
.btnCheck{
  width:210px;
  height: 52px;
  background: linear-gradient(#7abbff,#45baff);
  display: flex;
  align-items: center;
  border-radius: 26px;
  justify-content: center;
  color: #fff;
  font-size: 24px;
  font-weight: bold;
  cursor: pointer;
}
.btnCheck:hover{
  background: linear-gradient(#46baff,#45baff);
}
.taskIn{
  display: flex;
  flex-direction: column;
  width:500px;
  margin-top: 20px;
  margin-left: 50px;
  position:relative
}
.taskInTitle{
  margin-bottom: 10px;
  margin-left: -32px;
}
.templeteInfo{
  width:100%;
  min-height: 60px;
  background: #f5f9fd;
  border:1px solid #dbe7f3;
  margin-top:10px;
  font-size: 13px;
  color: #444;
  padding:10px;
  line-height: 24px;
}
.radioBox{
  width:20px;
  height: 20px;
  background: red;
  position: absolute;
  left: -30px;
}
.taskEditLine{
  width: 100%;
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}
.taskEditLine span.label{
  width:112px;
  flex-shrink: 0;
  font-size: 14px;
}

</style>
<style >
.taskInTitle .el-radio__label{
  font-size: 18px;
  color: #333333;
  font-weight: bold;
}
.taskInTitle .el-radio{
  display: flex;
  align-items: center;
}
.taskInTitle .el-radio__inner{
  border:none;
  border-radius: 0;
  width: 20px;
  height: 20px;
  background: #deebf6;
}
.taskInTitle .el-radio__inner::after{
  width: 8px;
    height: 8px;
    border-radius: 0;
}
.taskInForm .el-form-item {
  margin-bottom: 8px;
}
.taskInForm .el-form-item .el-form-item__label{
  width:112px;
  font-size: 14px;
  font-weight: normal;
  text-align: left;
}
.taskInForm .el-form-item .el-form-item__error{
  display: block;
  width: 100px;
  color: #ff4949;
  font-size: 12px;
  position: absolute;
  top: 8px;
  left: 102%;
}
.memberIn{
  display: flex;
  height: 476px;
  border-top: 1px solid #ddd;
}
.memberIn-left{
  width:260px;
  border-right: 1px solid #ddd;
}
.memberIn-right{
  flex:1;
}
.memberBox .el-dialog__body{
  padding:0px 20px 20px
}
.selectedLine{
  border-top: 1px solid #ddd;
}
.selectedLine span{
  border:1px solid #7abbff;
  background: #f6faff;
  padding:2px 10px;
  margin-right: 6px;
}
.memberIn-right .el-table--medium th, .el-table--medium td {
    padding: 7px 0;
}
.members-selectedLine{
  background: #fff;
  border:1px solid #dcdfe6;
  margin-top:6px;
  padding:6px 8px;
  border-radius: 5px;
}
.members-selectedLine span{
  margin-right: 8px;
}
</style>
